package com.itheima.health.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.ReportService;
import com.itheima.health.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ：seanyang
 * @date ：Created in 2019/6/29
 * @description ：报表控制器
 * @version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/report")
public class ReportController {

	@Reference
	private MemberService memberService;

	@Reference
	private SetmealService setmealService;

	@Reference
	private ReportService reportService;

	/*
	性别占比封装展示
	/report/getPercentByGender.do
	* */
	@RequestMapping("/getPercentByGender")
	public Result getPercentByGender(){
		return reportService.getGenderPercent();
	}
	/**
	 * 年龄占比封装展示
	 * /report/getPercentByAge.do
	 */
    @RequestMapping("/getPercentByAge")
	public Result getPercentByAge(){
		return reportService.getAgePercent();
	}























	@RequestMapping("/getMemberReport")
	public Result getMemberReport(){
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH,-12);
		try{
		    List<String> monthList = new ArrayList<>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");
			for(int i=0;i!=12;i++){
				calendar.add(Calendar.MONTH,1);
				monthList.add(sdf.format(calendar.getTime()));
			}
			// 获取月份列表中月份的成员人数
			List<Integer> memberCount = memberService.findMemberCountByMonth(monthList);
			// 封装数据
			Map<String,Object> maps = new HashMap<>();
			maps.put("months",monthList);
			maps.put("memberCount",memberCount);
			return new Result(true, MessageConst.ACTION_SUCCESS,maps);
		}catch(Exception e){
		    e.printStackTrace();
		}
		return new Result(false,MessageConst.ACTION_FAIL);
	}

	@RequestMapping("/getSetmealReport")
	public Result getSetmealReport(){
		try{
			// 获取套餐占比数据
		    List<Map<String,Object>> setmealCountList = setmealService.findSetmealCount();
		    // 获取套餐名称
			List<String> setmealNames = new ArrayList<>();
			for(Map<String,Object> mapSetmeals:setmealCountList){
				String setmealName = (String) mapSetmeals.get("name");
				setmealNames.add(setmealName);
			}
			// 构建返回的数据
			Map<String,Object> mapData = new HashMap<>();
			mapData.put("setmealCount",setmealCountList);
			mapData.put("setmealNames",setmealNames);
			return new Result(true,MessageConst.ACTION_SUCCESS,mapData);
		}catch(Exception e){
		    e.printStackTrace();
		    return new Result(false, MessageConst.ACTION_FAIL);
		}
	}

	@RequestMapping("/getBusinessReportData")
	public Result getBusinessReportData(){

		try{
			Map<String,Object> result = reportService.getBussinessReport();
			return new Result(true,MessageConst.ACTION_SUCCESS,result);
		}catch(Exception e){
		    e.printStackTrace();
		    return new Result(false,MessageConst.ACTION_FAIL);
		}
	}

	/**
	 * 1. 调用Service，获取统计数据
	 * 2. 获得报表日期
	 * 3. 获取与会员有关数据 (今日、本周、本月、总人数)
	 * 4. 获取与预约有关数据 (今日、本周、本月)
	 * 5. 获得到诊相关数据 (今日、本周、本月)
	 * 6. 获得套餐热门数据
	 * 7. 利用POIUtils写入数据到Excel
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/exportBusinessReport")
	public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
		try{
			Map<String,Object> result = reportService.getBussinessReport();
			System.out.println("result:"+result);
			// 获取报表日期
			String orderDate = (String)result.get("reportDate");
			// 获取会员相关数据
			Integer todayNewMember = (Integer) result.get("todayNewMember");
			Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
			Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
			Integer totalMember = (Integer) result.get("totalMember");
			// 获取预约相关数据
			Integer todayOrderNumber = (Integer)result.get("todayOrderNumber");
			Integer thisWeekOrderNumber = (Integer)result.get("thisWeekOrderNumber");
			Integer thisMonthOrderNumber = (Integer)result.get("thisMonthOrderNumber");
			// 获取到诊相关数据
			Integer todayVisitsNumber = (Integer)result.get("todayVisitsNumber");
			Integer thisWeekVisitsNumber = (Integer)result.get("thisWeekVisitsNumber");
			Integer thisMonthVisitsNumber = (Integer)result.get("thisMonthVisitsNumber");
			// 获取套餐数据
			List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
			// 使用POI，把数据写入Excel文件,构建sheet对象
			InputStream excelFileFile =  this.getClass().getResourceAsStream("/report_template.xlsx");
			XSSFWorkbook workbook = new XSSFWorkbook(excelFileFile);
			XSSFSheet sheet = workbook.getSheetAt(0);

			// 获取报表日期行(下表从0开始)
			XSSFRow row = sheet.getRow(2);
			row.getCell(5).setCellValue(orderDate);
			// 获取新增会员及会员总数
			row = sheet.getRow(4);
			row.getCell(5).setCellValue(todayNewMember);
			row.getCell(7).setCellValue(todayNewMember);

			// 获取今日预约及到诊数行
			row = sheet.getRow(7);
			row.getCell(5).setCellValue(todayOrderNumber);
			row.getCell(7).setCellValue(todayVisitsNumber);

			// 获取本周预约及本周到诊行
			row = sheet.getRow(8);
			row.getCell(5).setCellValue(thisWeekOrderNumber);
			row.getCell(7).setCellValue(thisWeekVisitsNumber);

			// 获取本月预约及本月到诊行
			row = sheet.getRow(9);
			row.getCell(5).setCellValue(thisMonthOrderNumber);
			row.getCell(7).setCellValue(thisMonthVisitsNumber);

			// 动态写入套餐数据
			int rowStartNum = 12;
			for(Map map:hotSetmeal){
				String name = (String)map.get("name");
				Long setmealCount = (Long)map.get("setmeal_count");
				BigDecimal proportion = (BigDecimal) map.get("proportion");
				row = sheet.getRow(rowStartNum);
				row.getCell(4).setCellValue(name);
				row.getCell(5).setCellValue(setmealCount);
				row.getCell(6).setCellValue(proportion.doubleValue());
				rowStartNum++;
			}


			// 下载文件
			ServletOutputStream out = response.getOutputStream();
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("content-Disposition","attachment;filename="+orderDate+"_report.xlsx");
			workbook.write(out);
			out.flush();
			out.close();
			workbook.close();
			return  null;
		}catch(Exception e){
		    e.printStackTrace();
		    return new Result(false,MessageConst.ACTION_FAIL);
		}
	}
}
